import React, { useState, useRef, useEffect } from "react";
import { useParams } from "@umijs/max";
import { useModel } from "@umijs/max";
import Webcam from 'react-webcam';
import { Button, Row, Col, Card, message, List, Typography, Input } from "antd";
import { AudioOutlined, VideoCameraOutlined, MessageOutlined, HistoryOutlined, SendOutlined } from '@ant-design/icons';
import AudioRecorder from "@/components/AudioRecorder";
import { startInterview, stop } from "@/services/swagger/interviewController";
import { getConversionByPage } from "@/services/swagger/conversionController";

const { Title, Text } = Typography;
const { TextArea } = Input;

const Start: React.FC = () => {
  const { interviewId } = useParams<{interviewId: any}>();
  const initialState = useModel("@@initialState");
  const currentUser = initialState.initialState?.currentUser;
  const [audioBlob, setAudioBlob] = useState<Blob | null>(null);
  const [isShow, setIsShow] = useState<boolean>(true);
  const [conversationHistory, setConversationHistory] = useState<Array<{
    id?: number;
    speaker: 'user' | 'ai';
    content: string;
    timestamp: string;
    messageType?: string;
    isStreaming?: boolean; // 标记是否正在流式显示
  }>>([]);
  const [inputMessage, setInputMessage] = useState<string>('');
  const [isInterviewStarted, setIsInterviewStarted] = useState<boolean>(false);
  const [isReceivingResponse, setIsReceivingResponse] = useState<boolean>(false);
  const [isSseConnected, setIsSseConnected] = useState<boolean>(false);
  const streamingMessageRef = useRef<string>(''); // 用于存储当前正在流式显示的消息
  const streamingIntervalRef = useRef<any>(null); // 用于控制打字机效果的定时器
  const lastMessageIdRef = useRef<number>(0); // 用于跟踪最后一条消息的ID
  const eventSourceRef = useRef<any>(null); // 用于存储SSE连接

  // 获取真实的对话历史
  const loadConversationHistory = async () => {
    try {
      const response = await getConversionByPage({
        current: 1,
        pageSize: 50,
        interviewId: interviewId || '0', // 使用字符串避免 Node.js 精度丢失
        userId: currentUser?.id || 1 // 使用当前登录用户的ID
      });

      if (response.code === 0 && response.data?.records) {
        const history = response.data.records.map(record => ({
          id: record.id,
          speaker: (record.messageType === 'user' ? 'user' : 'ai') as const,
          content: record.message || '',
          timestamp: record.createTime || new Date().toLocaleString(),
          messageType: record.messageType
        }));
        setConversationHistory(history);
      }
    } catch (error) {
      console.error('获取对话历史失败:', error);
    }
  };

  // SSE连接处理器 - 直接使用POST接口创建SSE连接
  const setupSSEConnection = () => {
    try {
      // 关闭之前的SSE连接
      if (eventSourceRef.current) {
        eventSourceRef.current.close();
        eventSourceRef.current = null;
      }

      const token = currentUser?.token || localStorage.getItem('token') || 'mock-token';

      // 由于后端是通过POST返回SseEmitter，我们需要在API调用时处理SSE
      setIsSseConnected(true);

      return true;
    } catch (error) {
      setIsSseConnected(false);
      return false;
    }
  };

    // 开始面试
  const handleStartInterview = async () => {
    try {
      setIsInterviewStarted(true);
      message.success('面试已开始，等待AI欢迎语...');

      // 加载对话历史
      await loadConversationHistory();

      // 直接调用SSE处理函数开始面试
      await sendUserMessage('开始面试');

    } catch (error) {
      console.error('开始面试失败（前端错误）:', error);

      // 即使前端API调用失败，也强制开始面试
      setIsInterviewStarted(true);
      message.success('面试已开始（离线模式）');

      // 加载对话历史
      await loadConversationHistory();

      // 添加备用欢迎消息
      const welcomeMessage = {
        speaker: 'ai' as const,
        content: '你好，欢迎参加模拟面试，请做个自我介绍。',
        timestamp: new Date().toLocaleString(),
        messageType: 'ai'
      };
      setConversationHistory(prev => [...prev, welcomeMessage]);
    }
  };

  // 停止面试
  const handleStopInterview = async () => {
    try {
      setIsReceivingResponse(false);

      // 关闭SSE连接
      if (eventSourceRef.current) {
        eventSourceRef.current.close();
        eventSourceRef.current = null;
        setIsSseConnected(false);
      }

      // 清除打字机效果
      if (streamingIntervalRef.current) {
        clearInterval(streamingIntervalRef.current);
        streamingIntervalRef.current = null;
      }

      // 关闭摄像头
      setIsShow(false);

      // 清理音频数据
      if (audioBlob) {
        URL.revokeObjectURL(URL.createObjectURL(audioBlob));
        setAudioBlob(null);
      }

      // 调用停止接口
      const response = await stop({
        userId: currentUser?.id || 1,
        interviewId: interviewId || '0',
        message: '结束面试'
      });

      if (response.code === 0) {
        setIsInterviewStarted(false);
        setIsReceivingResponse(false);
        message.success('面试已结束');

        // 添加结束提示消息
        const endMessage = {
          id: Date.now(),
          speaker: 'ai' as const,
          content: '模拟面试已结束，感谢您的参与！',
          timestamp: new Date().toLocaleString(),
          messageType: 'ai'
        };
        setConversationHistory(prev => [...prev, endMessage]);
      }
    } catch (error) {
      console.error('结束面试失败:', error);
      message.error('结束面试失败，请重试');

      // 即使后端调用失败，也更新前端状态并清理资源
      setIsInterviewStarted(false);
      setIsReceivingResponse(false);

      // 确保SSE连接已关闭
      if (eventSourceRef.current) {
        eventSourceRef.current.close();
        eventSourceRef.current = null;
        setIsSseConnected(false);
      }

      // 关闭摄像头
      setIsShow(false);

      // 清理音频数据
      if (audioBlob) {
        URL.revokeObjectURL(URL.createObjectURL(audioBlob));
        setAudioBlob(null);
      }
    }
  };

  // 发送用户消息到后端并接收流式回复
  const sendUserMessage = async (content: string) => {
    try {
      setIsReceivingResponse(true);

      // 手动创建POST请求来处理SSE流
      const token = currentUser?.token || localStorage.getItem('token') || 'mock-token';
      const requestData = {
        userId: currentUser?.id || 1,
        interviewId: interviewId || '0',
        message: content
      };

      const response = await fetch('http://localhost:8081/api/interview/start', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify(requestData),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      // 检查响应是否是SSE流
      const contentType = response.headers.get('content-type');
      if (contentType && contentType.includes('text/event-stream')) {
        const reader = response.body?.getReader();
        const decoder = new TextDecoder();
        let buffer = '';

        if (reader) {
          // 开始一个新的AI消息
          const messageId = Date.now();
          let isFirstChunk = true;
          let messageStarted = false;

          while (true) {
            const { done, value } = await reader.read();
            if (done) {
              setIsReceivingResponse(false);

              // 移除流式显示标记
              if (messageStarted) {
                setConversationHistory(prev => {
                  const updatedHistory = [...prev];
                  const lastMessage = updatedHistory[updatedHistory.length - 1];
                  if (lastMessage?.speaker === 'ai' && lastMessage?.isStreaming) {
                    updatedHistory[updatedHistory.length - 1] = {
                      ...lastMessage,
                      isStreaming: false
                    };
                  }
                  return updatedHistory;
                });
              }

              break;
            }

            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split('\n');
            buffer = lines.pop() || ''; // 保存最后一行（可能不完整）

            for (const line of lines) {
              if (line.trim() === '') continue;

              // 处理SSE数据格式
              if (line.startsWith('data:')) {
                const data = line.slice(5).trim();

                // 检查是否是结束标记
                if (data === '[DONE]') {
                  continue;
                }

                if (data) {
                  if (!messageStarted) {
                    // 第一个数据块，开始新消息
                    startTypingEffect(data, messageId);
                    messageStarted = true;
                  } else {
                    // 后续数据块，追加到当前正在流式显示的消息
                    appendToStreamingMessage(data);
                  }
                }
              }
            }
          }
        }
      } else {
        // 如果不是SSE流，作为普通响应处理
        const result = await response.json();
        setIsReceivingResponse(false);
      }

    } catch (error) {
      message.info('消息发送失败，请稍后重试');
      setIsReceivingResponse(false);
    }
  };

  // 开始流式显示消息
  const startTypingEffect = (content: string, messageId: number) => {
    // 清除之前的定时器
    if (streamingIntervalRef.current) {
      clearInterval(streamingIntervalRef.current);
    }

    // 创建新的消息项，初始内容为接收到的内容
    const newMessage = {
      id: messageId,
      speaker: 'ai' as const,
      content: content,
      timestamp: new Date().toLocaleString(),
      messageType: 'ai',
      isStreaming: true
    };

    // 添加新消息到对话历史
    setConversationHistory(prev => [...prev, newMessage]);

    // 设置当前流式消息的内容
    streamingMessageRef.current = content;
  };

  // 追加流式消息内容
  const appendToStreamingMessage = (chunk: string) => {
    streamingMessageRef.current += chunk;

    // 直接追加到最后一条AI消息
    setConversationHistory(prev => {
      const updatedHistory = [...prev];
      const lastMessage = updatedHistory[updatedHistory.length - 1];
      if (lastMessage?.speaker === 'ai' && lastMessage?.isStreaming) {
        updatedHistory[updatedHistory.length - 1] = {
          ...lastMessage,
          content: streamingMessageRef.current
        };
      }
      return updatedHistory;
    });
  };

  // 组件卸载时清除定时器
  useEffect(() => {
    return () => {
      if (streamingIntervalRef.current) {
        clearInterval(streamingIntervalRef.current);
      }
    };
  }, []);

  // 滚动到最新消息的效果
  useEffect(() => {
    const messageContainer = document.querySelector('[style*="flex: 1"]');
    if (messageContainer) {
      const scrollContainer = messageContainer.querySelector('[style*="overflowY: auto"]') || messageContainer;
      scrollContainer.scrollTop = scrollContainer.scrollHeight;
    }
  }, [conversationHistory]);

  const handleRecordingComplete = (blob: Blob) => {
    setAudioBlob(blob);

    // 添加用户消息到对话历史
    const newMessage = {
      speaker: 'user' as const,
      content: '[语音回答]',
      timestamp: new Date().toLocaleString(),
      messageType: 'user'
    };
    setConversationHistory(prev => [...prev, newMessage]);

    try {
      // 将音频转换为文本或直接发送语音数据
      const reader = new FileReader();
      reader.onload = async () => {
        const audioData = reader.result;

        // 通过HTTP API发送语音数据
        const response = await startInterview({
          userId: currentUser?.id || 1,
          interviewId: interviewId || '0',
          message: '[语音消息]'
        });

        message.info('语音已发送，等待AI回复...');
      };
      reader.readAsDataURL(blob);
    } catch (error) {
      message.error('语音发送失败');
    }
  };

  const sendTextMessage = (content: string) => {
    if (content.trim() === '') return;

    if (isReceivingResponse) {
      void message.warning('AI正在回复中，请等待后再发送消息');
      return;
    }

    // 发送用户消息到后端
    void sendUserMessage(content.trim());

    // 添加用户消息到对话历史
    const newMessage = {
      id: Date.now(),
      speaker: 'user' as const,
      content: content.trim(),
      timestamp: new Date().toLocaleString(),
      messageType: 'user'
    };
    setConversationHistory(prev => [...prev, newMessage]);

    // 清空输入框
    setInputMessage('');
  };

  // 页面加载时检查面试状态
  useEffect(() => {
    if (interviewId) {
      // 加载对话历史
      loadConversationHistory();
    }
  }, [interviewId]);

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      setIsReceivingResponse(false);
      setIsSseConnected(false);
      setIsInterviewStarted(false);

      // 清理定时器
      if (streamingIntervalRef.current) {
        clearInterval(streamingIntervalRef.current);
      }

      // 关闭SSE连接
      if (eventSourceRef.current) {
        eventSourceRef.current.close();
      }

      // 关闭摄像头
      setIsShow(false);

      // 清理音频数据
      if (audioBlob) {
        URL.revokeObjectURL(URL.createObjectURL(audioBlob));
        setAudioBlob(null);
      }
    };
  }, []);

  return (
    <div style={{ padding: '20px', background: '#f0f2f5', minHeight: '100vh' }}>
      <style>
        {`
          @keyframes blink {
            0%, 50% { opacity: 1; }
            51%, 100% { opacity: 0; }
          }
        `}
      </style>
      {/* 面试控制栏 */}
      <div style={{ textAlign: 'center', marginBottom: '20px' }}>
        <Title level={1}>🎤 AI数字人模拟面试</Title>
        <div style={{ display: 'flex', justifyContent: 'center', gap: '16px', marginBottom: '16px' }}>
          <Button
            type="primary"
            size="large"
            onClick={handleStartInterview}
            disabled={isInterviewStarted}
            style={{ background: '#52c41a', borderColor: '#52c41a' }}
          >
            开始面试
          </Button>
          <Button
            type="primary"
            size="large"
            danger
            onClick={handleStopInterview}
            disabled={!isInterviewStarted}
          >
            结束面试
          </Button>
        </div>
        <div style={{ display: 'flex', gap: '24px', justifyContent: 'center', alignItems: 'center' }}>
          <Text type={isInterviewStarted ? 'success' : 'secondary'} style={{ fontSize: '16px', fontWeight: 'bold' }}>
              📋 面试状态: {isInterviewStarted ? '进行中✓' : '未开始'}
          </Text>
          <Text type={isSseConnected ? 'success' : 'secondary'} style={{ fontSize: '14px' }}>
            🌐 AI回复: {isSseConnected ? '实时流式' : '等待连接'}
          </Text>
        </div>
      </div>

      {/* 新的布局：左侧大对话框，右上角视频区域 */}
      <div style={{ display: 'flex', gap: '16px', height: 'calc(100vh - 180px)' }}>
        {/* 左侧对话区域 - 占据主要空间 */}
        <Card
          title={
            <span>
              <HistoryOutlined style={{ marginRight: '8px' }} />
              实时对话
            </span>
          }
          style={{
            flex: 1,
            minHeight: '600px',
            display: 'flex',
            flexDirection: 'column'
          }}
        >
          {/* 对话历史 - 占据大部分空间 */}
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
            {/* 对话历史显示区域 */}
            <div style={{
              flex: 1,
              overflowY: 'auto',
              border: '1px solid #d9d9d9',
              borderRadius: '6px',
              padding: '16px',
              marginBottom: '16px',
              background: '#fafafa'
            }}>
              {conversationHistory.length === 0 ? (
                <div style={{
                  textAlign: 'center',
                  padding: '60px',
                  color: '#999',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  height: '100%'
                }}>
                  <MessageOutlined style={{ fontSize: '64px', marginBottom: '16px', color: '#d9d9d9' }} />
                  <div style={{ fontSize: '16px' }}>暂无对话记录</div>
                  <div style={{ fontSize: '14px', marginTop: '8px' }}>开始面试后，AI将向您提问</div>
                </div>
              ) : (
                <List
                  dataSource={conversationHistory}
                  renderItem={(item) => (
                    <List.Item style={{
                      border: 'none',
                      padding: '16px',
                      background: item.speaker === 'ai' ? '#f8f9fa' : '#e6f7ff',
                      borderRadius: '12px',
                      marginBottom: '12px',
                      position: 'relative',
                      boxShadow: '0 1px 3px rgba(0,0,0,0.1)'
                    }}>
                      {/* 正在输入光标效果 */}
                      {item.isStreaming && (
                        <div style={{
                          position: 'absolute',
                          right: '16px',
                          top: '16px',
                          display: 'flex',
                          alignItems: 'center',
                          background: 'rgba(24, 144, 255, 0.1)',
                          padding: '4px 8px',
                          borderRadius: '4px'
                        }}>
                          <div style={{
                            width: '8px',
                            height: '16px',
                            background: '#1890ff',
                            animation: 'blink 1s infinite',
                            marginRight: '6px'
                          }} />
                          <span style={{ fontSize: '12px', color: '#1890ff', fontWeight: '500' }}>
                            AI正在输入...
                          </span>
                        </div>
                      )}
                      <List.Item.Meta
                        avatar={
                          <div style={{
                            width: '40px',
                            height: '40px',
                            borderRadius: '50%',
                            background: item.speaker === 'ai' ? '#1890ff' : '#52c41a',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            color: 'white',
                            fontWeight: 'bold',
                            fontSize: '14px'
                          }}>
                            {item.speaker === 'ai' ? 'AI' : '我'}
                          </div>
                        }
                        title={
                          <div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>
                            {item.timestamp}
                          </div>
                        }
                        description={
                          <div style={{
                            fontSize: '15px',
                            color: '#333',
                            lineHeight: '1.6',
                            wordWrap: 'break-word'
                          }}>
                            {item.content}
                            {/* 光标闪烁效果 */}
                            {item.isStreaming && (
                              <span style={{
                                display: 'inline-block',
                                width: '2px',
                                height: '18px',
                                background: '#1890ff',
                                marginLeft: '2px',
                                animation: 'blink 1s infinite',
                                verticalAlign: 'middle'
                              }} />
                            )}
                          </div>
                        }
                      />
                    </List.Item>
                  )}
                />
              )}
            </div>

            {/* 文本输入区域 */}
            <div style={{
              display: 'flex',
              gap: '12px',
              padding: '16px',
              background: '#fff',
              border: '1px solid #d9d9d9',
              borderRadius: '8px'
            }}>
              <TextArea
                value={inputMessage}
                onChange={(e) => setInputMessage(e.target.value)}
                placeholder="输入您的问题或回答..."
                rows={3}
                disabled={!isInterviewStarted}
                style={{ flex: 1, fontSize: '14px' }}
                onPressEnter={(e) => {
                  e.preventDefault();
                  sendTextMessage(inputMessage);
                }}
              />
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={() => sendTextMessage(inputMessage)}
                disabled={!isInterviewStarted || !inputMessage.trim()}
                style={{
                  height: 'auto',
                  alignSelf: 'flex-end',
                  padding: '12px 16px'
                }}
              >
                发送
              </Button>
            </div>
          </div>
        </Card>

        {/* 右侧功能区 - 垂直排列 */}
        <div style={{ width: '320px', display: 'flex', flexDirection: 'column', gap: '16px' }}>
          {/* 摄像头区域 */}
          <Card
            title={
              <span>
                <VideoCameraOutlined style={{ marginRight: '8px' }} />
                摄像头
              </span>
            }
            extra={
              <Button
                size="small"
                type={isShow ? "default" : "primary"}
                icon={<VideoCameraOutlined />}
                onClick={() => setIsShow(prev => !prev)}
                disabled={!isInterviewStarted}
              >
                {isShow ? '关闭' : '开启'}
              </Button>
            }
            style={{ flex: 1 }}
          >
            <div style={{
              textAlign: 'center',
              height: '240px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}>
              {isShow && isInterviewStarted ? (
                <div style={{
                  position: 'relative',
                  width: '100%',
                  height: '100%'
                }}>
                  <Webcam
                    style={{
                      borderRadius: '8px',
                      boxShadow: '0 4px 8px rgba(0,0,0,0.1)',
                      width: '100%',
                      height: '100%',
                      objectFit: 'cover'
                    }}
                  />
                </div>
              ) : (
                <div style={{
                  width: '100%',
                  height: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  background: '#f5f5f5',
                  borderRadius: '8px'
                }}>
                  <Text type="secondary">
                    {!isInterviewStarted ? '请先开始面试' : '摄像头已关闭'}
                  </Text>
                </div>
              )}
            </div>
          </Card>

          {/* 录音控制区域 */}
          <Card
            title={
              <span>
                <AudioOutlined style={{ marginRight: '8px' }} />
                录音控制
              </span>
            }
          >
            <div style={{ textAlign: 'center' }}>
              <div style={{ marginBottom: '12px' }}>
                <AudioRecorder onRecordingComplete={handleRecordingComplete} disabled={!isInterviewStarted} />
              </div>
              {audioBlob && (
                <div style={{ marginTop: '8px' }}>
                  <Text type="success" style={{ fontSize: '12px' }}>
                    ✓ 录音已完成 ({Math.round(audioBlob.size / 1024)} KB)
                  </Text>
                </div>
              )}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

export default Start;
